import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/wallet_provider.dart';
import '../models/wallet_model.dart';
import '../constants/wallet_constants.dart';
import '../widgets/network_selector_bottom_sheet.dart';
import 'wallet_creation_method_page.dart';
import 'wallet_detail_page.dart';

/// 钱包主页面
class WalletHomePage extends StatefulWidget {
  const WalletHomePage({Key? key}) : super(key: key);

  @override
  State<WalletHomePage> createState() => _WalletHomePageState();
}

class _WalletHomePageState extends State<WalletHomePage> with SingleTickerProviderStateMixin {
  bool _isRefreshing = false;
  late AnimationController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<WalletProvider>().initialize();
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      appBar: AppBar(
        title: const Text(
          'MyWallet',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: const Color(0xFF0A0E27),
        elevation: 0,
        actions: [
          IconButton(
            icon: RotationTransition(
              turns: _refreshController,
              child: const Icon(Icons.refresh, color: Colors.white),
            ),
            onPressed: _isRefreshing ? null : () async {
              if (_isRefreshing) return;
              
              setState(() {
                _isRefreshing = true;
              });
              
              // 开始旋转动画
              _refreshController.repeat();
              
              // 刷新数据
              await context.read<WalletProvider>().refreshWalletData();
              
              // 停止旋转动画
              _refreshController.stop();
              _refreshController.reset();
              
              if (mounted) {
                setState(() {
                  _isRefreshing = false;
                });
              }
            },
          ),
        ],
      ),
      body: Consumer<WalletProvider>(
        builder: (context, walletProvider, child) {
          if (walletProvider.isLoading) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF6C5CE7)),
              ),
            );
          }

          if (walletProvider.error != null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    size: 64,
                    color: Colors.red,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    walletProvider.error!,
                    style: const TextStyle(color: Colors.white),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () {
                      walletProvider.initialize();
                    },
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          if (walletProvider.wallets.isEmpty) {
            return _buildEmptyState();
          }

          return _buildWalletContent(walletProvider);
        },
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: const Color(0xFF6C5CE7).withOpacity(0.1),
                borderRadius: BorderRadius.circular(60),
              ),
              child: const Icon(
                Icons.account_balance_wallet_outlined,
                size: 64,
                color: Color(0xFF6C5CE7),
              ),
            ),
            const SizedBox(height: 32),
            const Text(
              '欢迎使用 MyWallet',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '创建或导入您的第一个钱包\n开始管理您的数字资产',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white70,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 48),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const WalletCreationMethodPage(),
                    ),
                  );
                },
                icon: const Icon(Icons.add_circle_outline, size: 24),
                label: const Text(
                  '添加钱包',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF6C5CE7),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 18),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建钱包内容
  Widget _buildWalletContent(WalletProvider walletProvider) {
    return Column(
      children: [
        // 网络选择器
        _buildNetworkSelector(walletProvider),
        
        // 钱包列表 - 使用 Consumer 实现局部刷新
        Expanded(
          child: Consumer<WalletProvider>(
            builder: (context, provider, child) {
              return ListView.builder(
                padding: const EdgeInsets.all(16),
                itemCount: provider.wallets.length,
                itemBuilder: (context, index) {
                  final wallet = provider.wallets[index];
                  final isCurrent = wallet.id == provider.currentWallet?.id;
                  
                  return _buildWalletCard(wallet, isCurrent, provider);
                },
              );
            },
          ),
        ),
        
        // 底部操作按钮
        _buildBottomActions(),
      ],
    );
  }

  /// 构建网络选择器
  Widget _buildNetworkSelector(WalletProvider walletProvider) {
    final currentNetwork = WalletConstants.supportedNetworks[walletProvider.currentNetwork];
    
    return Container(
      margin: const EdgeInsets.all(16),
      child: Material(
        color: const Color(0xFF1E2139),
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          onTap: () => _showNetworkBottomSheet(walletProvider),
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.white.withOpacity(0.1)),
            ),
            child: Row(
              children: [
                const Icon(Icons.public, color: Color(0xFF6C5CE7)),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '当前网络',
                        style: TextStyle(
                          color: Colors.white54,
                          fontSize: 12,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        currentNetwork?.name ?? 'Unknown',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                const Icon(
                  Icons.arrow_drop_down,
                  color: Colors.white70,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 显示网络选择底部弹出框
  Future<void> _showNetworkBottomSheet(WalletProvider walletProvider) async {
    final selectedNetwork = await NetworkSelectorBottomSheet.show(
      context,
      currentNetwork: walletProvider.currentNetwork,
    );
    
    if (selectedNetwork != null && selectedNetwork != walletProvider.currentNetwork) {
      walletProvider.switchNetwork(selectedNetwork);
    }
  }

  /// 构建钱包卡片
  Widget _buildWalletCard(WalletModel wallet, bool isCurrent, WalletProvider walletProvider) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          // 统一使用 2px 边框，避免切换时大小变化
          color: isCurrent 
            ? const Color(0xFF6C5CE7)              // 选中：紫色边框
            : const Color(0xFF1E2139),             // 未选中：与背景相同的颜色
          width: 2,                                 // 统一 2px
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16), // 裁剪水波纹到圆角边界
        child: Material(
          color: isCurrent ? const Color(0xFF6C5CE7).withOpacity(0.1) : const Color(0xFF1E2139),
          child: InkWell(
            onTap: () {
              if (!isCurrent) {
                walletProvider.switchWallet(wallet);
              }
            },
            splashColor: const Color(0xFF6C5CE7).withOpacity(0.2), // 水波纹颜色
            highlightColor: const Color(0xFF6C5CE7).withOpacity(0.1), // 按压高亮颜色
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  // 钱包图标
                  Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: const Color(0xFF6C5CE7).withOpacity(0.2),
                      borderRadius: BorderRadius.circular(25),
                    ),
                    child: const Icon(
                      Icons.account_balance_wallet,
                      color: Color(0xFF6C5CE7),
                    ),
                  ),
                  const SizedBox(width: 16),
                  
                  // 钱包信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          wallet.name,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 18,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${wallet.address.substring(0, 6)}...${wallet.address.substring(wallet.address.length - 4)}',
                          style: const TextStyle(
                            color: Colors.white70,
                            fontSize: 14,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                color: const Color(0xFF6C5CE7).withOpacity(0.2),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Text(
                                WalletConstants.supportedNetworks[wallet.networkId]?.name ?? 'Unknown',
                                style: const TextStyle(
                                  color: Color(0xFF6C5CE7),
                                  fontSize: 12,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                            if (isCurrent) ...[
                              const SizedBox(width: 8),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                decoration: BoxDecoration(
                                  color: Colors.green.withOpacity(0.2),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: const Text(
                                  '当前',
                                  style: TextStyle(
                                    color: Colors.green,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ],
                          ],
                        ),
                      ],
                    ),
                  ),
                  
                  // 更多菜单
                  PopupMenuButton<String>(
                    icon: const Icon(Icons.more_vert, color: Colors.white70),
                    onSelected: (value) {
                      switch (value) {
                        case 'switch':
                          walletProvider.switchWallet(wallet);
                          break;
                        case 'view':
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => WalletDetailPage(wallet: wallet),
                            ),
                          );
                          break;
                        case 'delete':
                          _showDeleteDialog(wallet, walletProvider);
                          break;
                      }
                    },
                    itemBuilder: (context) => [
                      const PopupMenuItem(
                        value: 'view',
                        child: Row(
                          children: [
                            Icon(Icons.visibility, color: Colors.white70),
                            SizedBox(width: 8),
                            Text('查看详情', style: TextStyle(color: Colors.white)),
                          ],
                        ),
                      ),
                      if (!isCurrent)
                        const PopupMenuItem(
                          value: 'switch',
                          child: Row(
                            children: [
                              Icon(Icons.swap_horiz, color: Colors.white70),
                              SizedBox(width: 8),
                              Text('切换钱包', style: TextStyle(color: Colors.white)),
                            ],
                          ),
                        ),
                      const PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(Icons.delete, color: Colors.red),
                            SizedBox(width: 8),
                            Text('删除钱包', style: TextStyle(color: Colors.red)),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建底部操作
  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: Color(0xFF1E2139),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton.icon(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const WalletCreationMethodPage(),
              ),
            );
          },
          icon: const Icon(Icons.add_circle_outline),
          label: const Text('添加钱包'),
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFF6C5CE7),
            foregroundColor: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 18),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            elevation: 0,
          ),
        ),
      ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteDialog(WalletModel wallet, WalletProvider walletProvider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1E2139),
        title: const Text(
          '删除钱包',
          style: TextStyle(color: Colors.white),
        ),
        content: Text(
          '确定要删除钱包 "${wallet.name}" 吗？\n此操作不可撤销。',
          style: const TextStyle(color: Colors.white70),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(color: Colors.white70)),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              walletProvider.deleteWallet(wallet);
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}
